//
function base64ToUrl(base64Data, index) {
  const fileManager = uni.getFileSystemManager();

  // 创建临时文件路径
  const filePath = `${uni.env.USER_DATA_PATH}/image${Date.now()}.png`;

  // 将base64字符串转换为文件
  fileManager.writeFile({
    filePath: filePath,
    data: base64Data.split(",")[1], // 去掉base64数据的头部信息（如data:image/png;base64,）
    encoding: "base64",
    success: () => {
      if (index === 0) {
        wx.showShareImageMenu({
          path: filePath, //分享
        });
      }
      if (index === 1) {
        // 文件写入成功后保存到系统相册

        uni.saveImageToPhotosAlbum({
          filePath: filePath,
          success: () => {
            uni.showToast({
              title: "保存成功",
            });
          },
          fail: () => {
            uni.showToast({
              title: "保存失败",
              icon: "none",
            });
          },
        });
      }
    },
    fail: () => {
      uni.showToast({
        title: "转换失败",
        icon: "none",
      });
    },
  });
}

function replaceWhite(html) {
  // 处理富文本默认图片，视频大小
  if (!html) return "";
  let newContent = html
    .replace(/<video[^>]*>/gi, function (match, capture) {
      match = match
        .replace(/style="[^"]+"/gi, "")
        .replace(/style='[^']+'/gi, "");
      match = match
        .replace(/width="[^"]+"/gi, "")
        .replace(/width='[^']+'/gi, "");
      match = match
        .replace(/height="[^"]+"/gi, "")
        .replace(/height='[^']+'/gi, "");
      return match;
    })
    .replace(/<img[^>]*>/gi, function (match, capture) {
      match = match
        .replace(/style="[^"]+"/gi, "")
        .replace(/style='[^']+'/gi, "");
      match = match
        .replace(/width="[^"]+"/gi, "")
        .replace(/width='[^']+'/gi, "");
      match = match
        .replace(/height="[^"]+"/gi, "")
        .replace(/height='[^']+'/gi, "");
      return match;
    });
  newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
    match = match
      .replace(/width:[^;]+;/gi, "max-width:100%;")
      .replace(/width:[^;]+;/gi, "max-width:100%;");
    return match;
  });
  newContent = newContent.replace(/<br[^>]*\/>/gi, "");
  newContent = newContent
    .replace(
      /\<video/gi,
      '<video style="max-width:100%;height:auto;display:inline-block;margin:10rpx auto;"'
    )
    .replace(
      /\<img/gi,
      '<img style="max-width:100%;height:auto;display:inline-block;margin:10rpx auto;"'
    );
  return newContent;
}

module.exports = { base64ToUrl, replaceWhite };
